import UIKit
import SDWebImage
import Lottie
import TalkfunUtils

class TalkfunSharedTools: NSObject {
    //判断12小时 还是 24小时制
    static func is24HourFormat() -> Bool {
        let dateFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)
        if dateFormat?.range(of: "a") == nil {
            return true
        }
        
        return false
    }
    
    static func getTimeFormat()->String
    {
        // - 12 小时制;
        if (self.is24HourFormat() == true) {
          return "YYYY-MM-dd HH:mm:ss"
        }else
        {  //- 24 小时制；
        return "YYYY-MM-dd hh:mm:ss"
         
        }
    }
    static func timeIntervalTool(time:NSInteger)->NSArray
    {
        let beginTimestamp = time
        let endTimestamp = TalkfunSharedTools.getCurrentDateString()
            
        let timer1 = TimeInterval.init(beginTimestamp)
        let timer2 = TimeInterval.init(endTimestamp)
        
        let formatter = DateFormatter.init()
        formatter.dateStyle = DateFormatter.Style.medium
        formatter.timeStyle = DateFormatter.Style.short
        formatter.dateFormat = self.getTimeFormat()

        let date = NSDate.init(timeIntervalSince1970: timer1)
        let date2 = NSDate.init(timeIntervalSince1970: timer2)

        let calendar = NSCalendar.current
        let dateComponets2 = calendar.dateComponents([Calendar.Component.year , Calendar.Component.month,Calendar.Component.day ,Calendar.Component.hour,Calendar.Component.minute,Calendar.Component.second], from: date2 as Date, to: date as Date )
        //时
        var hour =  NSString(format: "%i", dateComponets2.hour!) as String
        if(dateComponets2.hour! < 10 )
        {
            hour = NSString(format: "0%i", dateComponets2.hour!) as String
        }
        
        //分
        var minute = NSString(format: "%i", dateComponets2.minute!) as String
        if(dateComponets2.minute! < 10 )
        {
            minute = NSString(format: "0%i", dateComponets2.minute!) as String
        }
        
        //秒
        var second = NSString(format: "%i", dateComponets2.second!) as String

        if(dateComponets2.second! < 10 )
        {
            second = NSString(format: "0%i", dateComponets2.second!) as String
        }
        
        return[hour,minute,second]
       
    }
    

    @objc static func timeDifference( endTime:NSInteger)-> NSString
    {
        let timeArray = self.timeIntervalTool(time: endTime)
        //时
        let hour =  timeArray[0] as! NSString
        //分
        let minute = timeArray[1] as! NSString
        //秒
        let second = timeArray[2] as! NSString

        let timeStr = NSString(format:"%@:%@:%@",hour,minute,second)
        // 获得某个时间的年月日时分秒
        return timeStr as NSString
    }
    
    //开始倒计时 duration = 3600
    @objc static func getCountdownWithTime(_ duration:NSInteger) -> NSString
    {
       
      var tmphh = NSString(format: "%ld", duration/3600)
        // 时
      if (tmphh.length == 1)
       {
          tmphh = NSString(format: "0%ld", duration/3600)
      }else{
          tmphh = "00"
      }

       //分
       var tmpmm = NSString(format: "%ld", (duration/60)%60)
       if (tmpmm.length == 1)
       {
           tmpmm = NSString(format: "0%ld", (duration/60)%60)
       }
       //秒

       var tmpss = NSString(format: "%ld", (duration)%60)
       if (tmpss.length == 1)
       {
            tmpss = NSString(format: "0%ld", (duration)%60)
       }
  
      let text = NSString(format:"%@:%@:%@",tmphh,tmpmm,tmpss)
        
        return text
    }
    //分 与 秒
    @objc static func minutesSndSeconds(_ duration:NSInteger) -> NSString
    {
         //分
         var tmpmm = NSString(format: "%ld", (duration/60)%60)
         if (tmpmm.length == 1)
         {
             tmpmm = NSString(format: "0%ld", (duration/60)%60)
         }
         //秒

         var tmpss = NSString(format: "%ld", (duration)%60)
         if (tmpss.length == 1)
         {
              tmpss = NSString(format: "0%ld", (duration)%60)
         }
    
        let text = NSString(format:"%@:%@",tmpmm,tmpss)
          
          return text
    }
    
    //计算字符高度
    @objc static func getSizeLabel(labelString:NSMutableAttributedString , labelWidth:CGFloat,labelfont:UIFont ) ->CGSize
    {
       
       let label = UILabel.init(frame:CGRect(x: 0, y: 0, width: labelWidth, height: 1.0))
        
        label.font = labelfont;
        label.numberOfLines = 0;
        label.attributedText = labelString;
        label.lineBreakMode = NSLineBreakMode.byCharWrapping;
    

        let attr: [NSAttributedString.Key : Any] = [.font: labelfont, ]

        labelString.addAttributes(attr, range: NSRange(location: 0, length: labelString.length))
    
        let size = label.sizeThatFits(CGSize(width: label.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
       
        return size
    }

    //当前时间戳
    @objc static func getCurrentDateString()->NSInteger
    {
     
        //获取当前时间
        let  now =  NSDate ()
         
        // 创建一个日期格式器
        let  dformatter =  DateFormatter ()
        dformatter.dateFormat =  self.getTimeFormat()
      
      //  ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
        //设置时区,这个对于时间的处理有时很重要
        let timeZone = NSTimeZone.init(name: "Asia/Shanghai")
        dformatter.timeZone = timeZone as TimeZone?

        //当前时间的时间戳
        let  timeInterval: TimeInterval  = now.timeIntervalSince1970
        let  timeStamp =  Int (timeInterval)
       
        return timeStamp
    }
    @objc static func getTimestamp(mStr:NSString)->NSString
    {

        let interval = mStr.doubleValue
        
        let date = NSDate.init(timeIntervalSince1970: interval)
        let  dformatter = DateFormatter ()
        if self.is24HourFormat() == true {
            dformatter.dateFormat = "HH:mm"
        }else
        {
            dformatter.dateFormat = "hh:mm"
        }
             
        let timeZone = NSTimeZone.init(name: "Asia/Shanghai")
        dformatter.timeZone = timeZone as TimeZone?
        
        let dateString   = dformatter.string(from: date as Date)
        
        return dateString as NSString
        
    }
    
    // 65 == A
    @objc static func asciiBytesToString(inx: NSInteger) -> String{

        let num = 65 + inx

        let ch = Character(UnicodeScalar(num)!) as Character
        
        var str: String = ""
        
        str.append(ch)

        return str
    }
  
    @objc static func getOptionsCellLineSpacing(model:TalkfunSubjectExamineDetail)->CGFloat
    {
        //填空题
        if (model.subjectInfo.type == TalkfunTopicTypeStuff )
        {
            return 5.0
        }
        return 11.0 + 11.0
    }
    @objc static func randomColor() -> UIColor
    {
        let red = CGFloat(arc4random()%256)/255.0
        let green = CGFloat(arc4random()%256)/255.0
        let blue = CGFloat(arc4random()%256)/255.0
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
     }
    
    //返回的是总的秒数
    @objc static func timeDifferenceAllSecond( endTime:NSInteger)-> NSString
    {
        let beginTimestamp = endTime
        let endTimestamp = TalkfunSharedTools.getCurrentDateString()
            
       
        let timer1 = TimeInterval.init(beginTimestamp)
        let timer2 = TimeInterval.init(endTimestamp)
        
        let formatter = DateFormatter.init()
        formatter.dateStyle =  DateFormatter.Style.medium
        formatter.timeStyle = DateFormatter.Style.short
        formatter.dateFormat =  self.getTimeFormat()
        
        let timeZone = NSTimeZone.init(name: "Asia/Shanghai")
        formatter.timeZone = timeZone as TimeZone?
        
        
        let date = NSDate.init(timeIntervalSince1970: timer1)
        let date2 = NSDate.init(timeIntervalSince1970: timer2)

        let calendar = NSCalendar.current
        let dateComponets2 = calendar.dateComponents([Calendar.Component.year , Calendar.Component.month,Calendar.Component.day ,Calendar.Component.hour,Calendar.Component.minute,Calendar.Component.second], from: date2 as Date, to: date as Date )
      
        let secondTime  = dateComponets2.minute!*60 +  dateComponets2.second!
        var second = NSString(format: "%i",secondTime) as String

        if(secondTime < 10 )
        {
            second = NSString(format: "0%i", secondTime) as String
        }

        return second as NSString
    }
    
    //判断是不是刘海屏
    @objc static  func isFullScreen()-> Bool {
        
    if #available(iOS 11, *) {
            guard let w = UIApplication.shared.delegate?.window, let unwrapedWindow = w else {
              
                return false
            }
            
            if unwrapedWindow.safeAreaInsets.left > 0 || unwrapedWindow.safeAreaInsets.bottom > 0 {
                print(unwrapedWindow.safeAreaInsets)
             
                return true
            }
    }
    return false
   }

    @objc static func openUrl(str:NSString)
    
    {
        if ( str != nil) {
            
        let newURL = NSURL.init(string:str as String)
            
            if #available(iOS 10.0, *) {
                let window = UIApplication.shared.keyWindow
                if window != nil {
                    
                    
                let alert = UIAlertController.init(title: "提示", message: "是否打开链接?", preferredStyle:.alert)
                let cancel:UIAlertAction = UIAlertAction.init(title: "取消", style: .default) { action in
                    
                }
                alert.addAction(cancel)
                let otherAction:UIAlertAction = UIAlertAction.init(title: "确定", style: .default) { action in
                    
                    UIApplication.shared.open(newURL! as URL, options: [:], completionHandler: nil)
                }
                alert.addAction(otherAction)
                
              
                
                    if  UIDevice.current.model.hasPrefix("iPad") {
                        alert.popoverPresentationController?.sourceView = window
                        alert.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 1.0, height: 1.0)
                    }
                   
                    window?.rootViewController!.present(alert, animated: true)
                }else
                {
                    UIApplication.shared.open(newURL! as URL, options: [:], completionHandler: nil)
                }
                
              
            }
        }

    }
    @objc static func openUrl(image:UIImage)
    {
        if ( image != nil) {
        
            let  ciImage = CIImage.init(cgImage: (image.cgImage)!)

            let detector = CIDetector.init(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyHigh])
            
            let featuresArr = detector?.features(in: ciImage)

            //相片识别二维码
            if (featuresArr!.count > 0) {
                let feature:CIQRCodeFeature = featuresArr?[0] as! CIQRCodeFeature
                

            let scanResult = feature.messageString
                
   //NSLog(@"得到的链接%@",scanResult);
            self.openUrl(str: scanResult! as NSString)
           

            }
        }
        
    }

    @objc  static func keyWindow() -> UIWindow {
        if let window: UIWindow = (UIApplication.shared.delegate?.window)! {
            debugPrint(window)
            return window
        } else {
            if #available(iOS 13.0, *) {
                let arr: Set = UIApplication.shared.connectedScenes
                let windowScene: UIWindowScene = arr.first as! UIWindowScene
            //如果是普通APP开发，可以使用
            // SceneDelegate * delegate = (SceneDelegate *)windowScene.delegate;
               //UIWindow * mainWindow = delegate.window;
             if let mainWindow: UIWindow = windowScene.value(forKeyPath: "delegate.window") as? UIWindow {
                    return mainWindow
                } else {
                    return UIApplication.shared.windows.first!
                }
            }else{
                return UIApplication.shared.keyWindow!
            }
        }
    }
    
    @objc static func getLivingChatData(dict:TFChatData)->TF_LivingChatData
    {
        let model = TF_LivingChatData()
        model.chat = dict.chat
        model.gender = dict.gender
        model.uid = dict.uid
        model.a = dict.a
        model.time = dict.time
        model.gid = dict.gid
        model.avatar = dict.avatar
        model.isMe = dict.isMe
        model.role = dict.role
        model.term = dict.term
        model.nickname = dict.nickname
        model.msg = dict.msg
        model.xid = dict.xid
        model.attr = dict.attr
        model.attrDict = dict.attrDict
        model.replyList = dict.replyList
        model.imageURL = dict.imageURL
        model.money = dict.money
        model.uuid = dict.uuid
        
        return model;
    }
    @objc static func ExpressionsArray()->NSArray
    {
        return [    "slime",
                     "laugh",
                     "love",
                     "tongue",
                     "daze",
                     "handclap",
                     "titter",
                     "handssors",
                     "six",
                     "heart",
                     "melon",
                     "silly",
                     "like",
                     "dog",
                     "expect",
                     "flower"
                ]
    }
    //删除最后一个字符或者表情
    @objc static func GetTextMessage(_ text:NSString)->NSString
    {
        if(text.length==0)
        {
            return text
        }
        let expressionsArray = TalkfunSharedTools.ExpressionsArray()
        var match:Bool = false
        
        var range = NSRange(location: text.length - 1, length: 1)
        for i in 0..<expressionsArray.count {

            let srt:NSString = expressionsArray[i] as! NSString
           
            let predicateStr =  NSString.init(format: "[\\s\\S]*\\[%@\\]$", srt)
            
           let predicate = NSPredicate.init(format: "SELF MATCHES %@", predicateStr)
            
            match = predicate.evaluate(with: text)
            if (match) {
                
                let srt1:NSString = expressionsArray[i] as! NSString
                let str_length = srt1.length
                
                range =  NSRange(location: text.length - (str_length+2), length: str_length+2)

                break;
            }
    
       
    }
        let newMsg = text.replacingCharacters(in: range, with: "")
        
        return newMsg as NSString;
   
}
    
    //删除一些控制器
    @objc static func removeFromParentViewController(_ viewController:UIViewController,name:String)
    {
        if ((viewController.navigationController) != nil) {
            
            let tempVCA = viewController.navigationController?.viewControllers
            for i in 0..<tempVCA!.count {
          
                let tempVC:UIViewController = tempVCA![i] as UIViewController
                
                if(tempVC.TF_className == name)
                {
                    tempVC.removeFromParent()
                   
                }
            }
        }

    }
    
    //view转成image
    @objc static func imageWithUIView(_ view:UIView)->UIImage
    {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0);

        let ctx = UIGraphicsGetCurrentContext()

        view.layer.render(in: ctx!)
        let tImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tImage!;
    }
    //时 分  秒
    @objc static func getTimeStr(_ duration:CGFloat) -> NSString
    {
        let newDuration = NSInteger(duration)
   
        let hour   = newDuration / 3600;
        let minute = (newDuration - hour * 3600) / 60;
        let second = newDuration - minute * 60 - hour * 3600;
        
        let text = NSString(format:"%i:%i:%i",hour,minute,second)
        
        return text

    }
    @objc static func getMainScreen() -> CGRect

    {
        
    var superViewW = UIScreen.main.bounds.width
    var superViewH = UIScreen.main.bounds.height
        
    //1 ==螢幕直立
        let deviceOrientation = UIApplication.shared.statusBarOrientation
    
        if deviceOrientation == .portrait || deviceOrientation == .portraitUpsideDown
        
        {
            if (superViewH < superViewW) {
                  superViewH =  UIScreen.main.bounds.width
                  superViewW =  UIScreen.main.bounds.height
            }
        }else
        {
            
            
            
            if ( superViewW < superViewH) {
                
                
                  superViewH =  UIScreen.main.bounds.width
                  superViewW =  UIScreen.main.bounds.height
            }
        }
        
   
        
    return CGRect(x: 0, y: 0, width: superViewW, height: superViewH)

    }
    @objc static func getRectWith(_ name:String,size:CGSize,fontSize:CGFloat)->CGRect
    {
      return TalkfunUtils.getRectWith(name, size: size, fontSize: fontSize)
    }
    @objc static func isWhetherNoUrl(_ msg:String)-> Bool
    {
        return TalkfunUtils.isWhetherNoUrl(msg)
    }
    
    @objc static func getURLFromStr(_ msg:String)-> NSArray
    {
        return TalkfunUtils.getURLFromStr(msg) as NSArray
    }
    
    //生成图文富文本
    @objc static func getAttributedText(_ str:String,fontSize:UIFont,foregroundColor:UIColor)->NSMutableAttributedString
    
    {
        return TalkfunUtils.getAttributedText(str, fontSize: fontSize , foregroundColor: foregroundColor)
    }
    @objc static func assembleAttributeString(_ string:String,boundingSize:CGSize,fontSize:CGFloat,shadow:Bool)->NSDictionary
    {
        
        return TalkfunUtils.assembleAttributeString(string, boundingSize: boundingSize, fontSize: fontSize, shadow: shadow)! as NSDictionary
    }
    @objc static func getJsonDataJsonname(_ name:String)->AnimationView
    
    {
        let animation = Animation.named(name as String)
    
        let animationView = AnimationView()
        animationView.animation = animation
        animationView.play(fromProgress: 0, toProgress: 1, loopMode: .loop, completion: nil)
        animationView.contentMode = .scaleAspectFit
        animationView.backgroundColor = UIColor.clear
       return animationView
    }
    
    @objc static func sizeLabelToFit(_ aString:NSAttributedString,width:CGFloat,fontSize:UIFont)->CGSize
    {
        let tempLabel = UILabel.init(frame: CGRect(x: 0, y: 0, width: width, height: 0))
        tempLabel.font = fontSize
        tempLabel.attributedText = aString
        tempLabel.sizeToFit()
      
        let size = tempLabel.frame.size
  
        return  size
    }
}
